package com.useeinfo.oa.open.dashboard.security;

import com.alibaba.fastjson.JSONObject;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.data.SelectVO;
import com.useeinfo.framework.sugar.tools.StringConverters;
import com.useeinfo.oa.common.utils.ResultUtil.ResultDto;
import com.useeinfo.oa.common.utils.ResultUtil.ResultUtil;
import com.useeinfo.oa.modules.base.biz.PersonnelBiz;
import com.useeinfo.oa.modules.base.entity.Enterprise;
import com.useeinfo.oa.modules.base.entity.Organization;
import com.useeinfo.oa.modules.base.entity.Personnel;
import com.useeinfo.oa.modules.base.entity.Position;
import com.useeinfo.oa.modules.base.tools.EnterpriseTools;
import com.useeinfo.oa.modules.base.tools.OrganizationTools;
import com.useeinfo.oa.modules.security.biz.OrganizationBiz;
import com.useeinfo.oa.modules.security.entity.SystemUser;
import com.useeinfo.oa.modules.security.util.SessionKeyUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/web/admin/organization")
public class OrganizationAction {
    static Logger logger = LoggerFactory.getLogger(OrganizationAction.class);


    @Autowired
    private OrganizationBiz organizationBiz;
    @Autowired
    private PersonnelBiz personnelBiz;

    /**
     * list页面跳转
     *
     * @return
     */
    @RequestMapping("/list")
    public ModelAndView list() {

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("pages/system/organization/list");

        return modelAndView;
    }

    /**
     * 数据查询接口
     *
     * @param pageNowParam
     * @param pageSizeParam
     * @param organizationName
     * @param code
     * @return
     */
    @RequestMapping("/listJson")
    @ResponseBody
    public JSONObject listJson(@RequestParam(value = "pageNo", required = false) String pageNowParam,
                               @RequestParam(value = "pageSize", required = false) String pageSizeParam,
                               String organizationName, String code) {
        QueryParam queryParam = new QueryParam(pageNowParam, pageSizeParam);
        if (!StringConverters.null2String(organizationName).equals("")) {
            queryParam.getSqlMap().put("organizationName", organizationName);
        }
        if (!StringConverters.null2String(code).equals("")) {
            queryParam.getSqlMap().put("code", code);
        }
        return organizationBiz.findJSONList(queryParam);
    }

    /**
     * 编辑页面跳转
     *
     * @param id
     * @return
     */
    @RequestMapping("/editPage")
    public ModelAndView editPage(String id) {

        ModelAndView modelAndView = new ModelAndView();
        Organization organization = organizationBiz.findModel(StringConverters.null2Long(id));
        modelAndView.addObject("organization", organization);
        modelAndView.setViewName("pages/system/organization/edit");
        System.out.println(organizationBiz.getOrganizationMsg(id, null));
        return modelAndView;
    }

    /**
     * 编辑页面跳转--编辑子部门
     *
     * @param id
     * @return
     */
    @RequestMapping("/editChildPage")
    public ModelAndView editChildPage(String id) {

        ModelAndView modelAndView = new ModelAndView();
        Organization organization = organizationBiz.findModel(StringConverters.null2Long(id));
        modelAndView.addObject("organization", organization);
        modelAndView.setViewName("pages/system/organization/childEdit");
        return modelAndView;
    }

    /**
     * 编辑子部门————获取部门信息
     *
     * @param id
     * @return
     */
    @RequestMapping("/getOrganizationMsg")
    @ResponseBody
    public ResultDto getOrganizationMsg(String id, HttpServletRequest request) {
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
//        if (enterprise == null) {
//            return ResultUtil.error("登陆过期，请重新登录");
//        }


        return organizationBiz.getOrganizationMsg(id, enterprise);

        //Organization organization = organizationBiz.findModel(StringConverters.null2Long(id));

        // return ResultUtil.success();
    }


    /**
     * 数据保存接口
     *
     * @param organization
     * @return
     */
    @RequestMapping("/addOrUpdate")
    @ResponseBody
    public ResultDto addOrUpdate(Organization organization, String parentId) {
        try {
            return organizationBiz.addOrUpdateFirst(organization, "0");
        } catch (Exception e) {
            logger.info(e.getMessage());
            return ResultUtil.error();
        }
    }


    /**
     * 编辑页面跳转--编辑子部门
     *
     * @return
     */
    @RequestMapping("/organizeTreePage")
    public ModelAndView organizeTreePage() {

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("pages/system/organization/organizationTree");
        return modelAndView;
    }


    /**
     * 获取部门-选择框
     */
    @RequestMapping("/getOrganizationListMagic")
    @ResponseBody
    public List<SelectVO> getOrganizationListMagic(@RequestParam(value = "q", required = false) String q,
                                                   @RequestParam(value = "id", required = false) String id,HttpServletRequest request) {
        //下面保证默认选择项加载正常
        String index = "";
        boolean status = false;//表示默认list中无此id的数据
        Organization organization = organizationBiz.findModel(StringConverters.ToLong(id));
        if(StringUtils.isBlank(q)&&organization!=null){
            index = id;
        }
        List<SelectVO> selectVOS = new ArrayList<>();
        Enterprise enterprise=SessionKeyUtils.getSessionEnterprise(request);
        QueryParam queryParam = new QueryParam(1, 20);
        queryParam.getSqlMap().put("magicLike", q);
        queryParam.getSqlMap().put("magicId", id);
        queryParam.getSqlMap().put("enterpriseId", enterprise.getId()+"");
        List<Organization> organizations = organizationBiz.findList(queryParam);
        if(CollectionUtils.isNotEmpty(organizations)){
            for(Organization organization1 : organizations){
                if(StringUtils.isNotBlank(index)&&index.equals(organization1.getId()+"")){
                    status = true;
                }
                selectVOS.add(new SelectVO(organization1.getOrganizationName(), organization1.getId() + ""));
            }
        }
        if(!status&&organization!=null){
            selectVOS.add(new SelectVO(organization.getOrganizationName(), organization.getId() + ""));
        }
        return selectVOS;
    }


    /**
     * 编辑页面跳转--编辑子部门editChild.jsp
     *
     * @param id
     * @return
     */
    @RequestMapping("/addChildPage")
    public ModelAndView addChildPage(String id, String parentId, HttpServletRequest request) {

        ModelAndView modelAndView = new ModelAndView();
        Organization organization = organizationBiz.findModel(StringConverters.null2Long(id));
        modelAndView.addObject("organization", organization);

        modelAndView.addObject("parentId", parentId);
        modelAndView.setViewName("pages/system/organization/editChild");
        return modelAndView;
    }

    /**
     * 查看结构editChild.jsp
     */
    @RequestMapping("/viewTree")
    public ModelAndView viewTree() {

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("pages/system/organization/viewTree");
        return modelAndView;
    }


    /**
     * 部门管理中的新增子部门 接口
     * @param organization 组织
     * @param parentId  父节点
     * @param request  request
     * @return ResultDto
     */
    @RequestMapping("/saveChildPage")
    @ResponseBody
    public ResultDto saveChildPage(Organization organization, String parentId, HttpServletRequest request) {
        try {
            Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);

            return organizationBiz.addOrUpdate(organization, parentId, enterprise);
        } catch (Exception e) {
            logger.info(e.getMessage());
            return ResultUtil.error();
        }
    }

    /**
     * 获取所有组织
     */
    @RequestMapping("/getOrganizationTree")
    @ResponseBody
    public ResultDto getOrganizationTree(@RequestParam(value = "sysCode", required = false) String sysCode) {
        return organizationBiz.getOrganizationTree(sysCode);
    }


    /**
     * 组织架构---树结构数据
     * @param request
     * @return
     */
    @RequestMapping("/treeData")
    @ResponseBody
    public ResultDto treeData(HttpServletRequest request) {
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if (null == enterprise) {
            return ResultUtil.error("企业信息有误");
        }
        String hql = "select obj from Organization obj where obj.parentId=null and obj.deleteStatus = false and obj.enterprise.id=" + enterprise.getId();
        List<Organization> organizationList = organizationBiz.hqlExcute(hql);

        List<OrganizationTools> organizationToolsList = new ArrayList<>();
        for (Organization organization : organizationList) {
            if(getChildNode(organization.getId(), enterprise).size()>0) {
                organizationToolsList.add(new OrganizationTools(organization.getId(), organization.getOrganizationName(), getChildNode(organization.getId(), enterprise)));
            }else {
                organizationToolsList.add(new OrganizationTools(organization.getId(), organization.getOrganizationName(), null));
            }
        }
        List<OrganizationTools> firstNode = new ArrayList<>();
        firstNode.add(new OrganizationTools(-1,enterprise.getEnterpriseName(),organizationToolsList));
        return ResultUtil.success(firstNode);
    }

    /**
     * 递归子节点数据
     * @param id
     * @param enterprise
     * @return
     */
    public List<OrganizationTools> getChildNode(long id, Enterprise enterprise) {
        String hql = "select obj from Organization obj where obj.deleteStatus= false and obj.parentId=" + id + "and obj.enterprise.id=" + enterprise.getId();
        List<Organization> organizationList = organizationBiz.hqlExcute(hql);
        List<OrganizationTools> organizationToolsList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(organizationList)) {
            for (Organization organization : organizationList) {
                if(getChildNode(organization.getId(), enterprise).size()>0) {
                    organizationToolsList.add(new OrganizationTools(organization.getId(), organization.getOrganizationName(), getChildNode(organization.getId(), enterprise)));
                }else {
                    organizationToolsList.add(new OrganizationTools(organization.getId(), organization.getOrganizationName(), null));
                }
            }
        }
        return organizationToolsList;
    }


    /**
     * 删除部门
     *
     * @param id
     * @return
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ResultDto delete(String id,HttpServletRequest request) {
        Enterprise enterprise=SessionKeyUtils.getSessionEnterprise(request);
        Organization organization=organizationBiz.findModel(StringConverters.null2Long(id));
        QueryParam queryParam=new QueryParam();
        queryParam.getSqlMap().put("enterpriseId",enterprise.getId()+"");
        queryParam.getSqlMap().put("organizationId",id);
        List<Personnel> personnelList=personnelBiz.findList(queryParam);//该部门下有人员不能删除
        List<EnterpriseTools> organizationList=organizationBiz.getChildOrganization(organization);//该部门下有子部门不能删除
        if(CollectionUtils.isEmpty(personnelList)&&CollectionUtils.isEmpty(organizationList)){
            organization.setDeleteStatus(true);
            organizationBiz.addOrUpdate(organization);
            return ResultUtil.success();
        }else{
            return ResultUtil.error("该部门下有子部门或有人员，不能删除");
        }
    }

}
